import Dialog from '../../component/vant/dialog/dialog';
import Toast from '../../component/vant/toast/toast';
const app = getApp();
const api = require('../../api.js');
const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    actions: [
      {
        name: '分享给好友',
        openType: 'share'
      }
      // {
      //   name: '分享课程海报'
      // }
    ],
    text: '立即购买',
    standard_id: '',
    standard_name: '',
    domain: api.xh.downloadDomain,
    level: {
      1: '普通教师',
      2: '教学新秀',
      3: '教学能手',
      4: '学科带头人',
      5: '名教师',
      6: '名校长 ',
      7: '省特级教师'
    },
    treeData: [],
    expand: true,
    joined: 0,
    isIPX: app.globalData.isIPX,
    isIOS: app.globalData.isIOS,
    teacherTagStyle: util.teacherTagStyles,
    toView: 'chapter',
    activeView: 'chapter',
    loaded: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var curriculum_id = options.curriculum_id;
    var curriculum_name = options.curriculum_name;
    var school_id = '';

    var grade_id = wx.getStorageSync('current_grade_id');
    var course_id = wx.getStorageSync('current_course_id');

    var teacher_ids = [];
    var page = this;
    var from = options.from;
    page.setData({
      curriculum_id: curriculum_id
    });
    wx.setStorageSync('current_curriculum_id', curriculum_id);
    wx.setStorageSync('current_curriculum_name', curriculum_name);
    if (from != undefined) {
      page.setData({
        from: from,
        curriculum_name: curriculum_name
      });
    }

    //  获取课程详情
    app.sendRequest({
      url: api.course.curriculum_info,
      data: {
        curriculum_id: curriculum_id
      },
      success: function(res) {
        page.setData({ toastHidden: false });
        if (res.data != '') {
          for (var index in res.data.teacher_list) {
            teacher_ids.push(res.data.teacher_list[index].teacher_id);
          }
          teacher_ids = teacher_ids.join(',');
          school_id = res.data.school_id;
          if (res.data.now_cost == '' && page.data.text != '继续学习') {
            // 设置数据
            page.setData({
              text: '开始学习'
            });
          }

          if (teacher_ids.length > 0) {
            //  授课教师
            wx.request({
              url: api.teacher.list,
              data: {
                teacher_ids: teacher_ids
              },
              success(tea_res) {
                if (tea_res.data != '') {
                  // 设置数据
                  page.setData({
                    teacher_list: tea_res.data.data.list
                  });
                } else {
                  page.setData({
                    teacher_list: []
                  });
                }

                Toast.loading({
                  mask: false,
                  message: '加载中...'
                });
                setTimeout(() => {
                  new Promise(resolve => {
                    let query = wx.createSelectorQuery();
                    query.select('#chapter').boundingClientRect();
                    query.select('#teacher').boundingClientRect();
                    query.select('#school').boundingClientRect();
                    query.select('#courses').boundingClientRect();
                    query.exec(function(res) {
                      resolve(res);
                    });
                  }).then(res => {
                    page.setData({
                      chapterBoxTop: res[0].top,
                      teacherBoxTop: res[1].top,
                      schoolBoxTop: res[2].top,
                      coursesBoxTop: res[3].top,
                      loaded: 1
                    });
                    Toast.clear();
                  });
                }, 600);
              }
            });
          }

          //  相关课程
          wx.request({
            url: api.course.student_curriculum_list,
            data: {
              school_ids: school_id
            },
            success(course_res) {
              if (course_res.data != '') {
                // 设置数据
                page.setData({
                  hot_courses: course_res.data.data.list
                });
              } else {
                page.setData({
                  hot_courses: []
                });
              }
            }
          });

          //  机构介绍
          wx.request({
            url: api.school.info,
            data: {
              school_id: school_id
            },
            success(school_res) {
              if (school_res.data != '') {
                // 设置数据
                page.setData({
                  school_info: school_res.data.data
                });
              } else {
                page.setData({
                  school_info: []
                });
              }
            }
          });

          //  课程大纲
          app.sendRequest({
            url: api.public.outline_directory,
            data: {
              curriculum_id: curriculum_id
            },
            success(directory_res) {
              if (
                directory_res.data != '' &&
                directory_res.data.list != undefined
              ) {
                // 设置数据
                page.setData({
                  treeData: directory_res.data.list
                });
              } else {
                page.setData({
                  msg: '暂无目录',
                  treeData: []
                });
              }
            }
          });

          // 设置数据
          page.setData({
            toastHidden: false,
            course_info: res.data
          });
        } else {
          page.setData({
            toastHidden: false,
            course_info: []
          });
        }
      }
    });

    this._observer = wx.createIntersectionObserver(this);
    this._observer.relativeTo('.jump-list').observe('.course-info', res => {
      this.setData({
        appear: res.intersectionRatio > 0
      });
    });
  },
  updateStudyPro() {
    let page = this;
    //  学习进度
    app.sendRequest({
      url: api.course.study_plan,
      data: {
        curriculum_id: page.data.curriculum_id
      },
      success(plan_res) {
        if (JSON.stringify(plan_res.data) != '{}') {
          // 设置数据
          page.setData({
            joined: 1,
            standard_id: plan_res.data.standard_id,
            standard_name: plan_res.data.standard_name,
            text: '继续学习'
          });
        } else {
          page.setData({
            standard_id: ''
          });
        }
      }
    });
  },
  jumpTo(e) {
    var page = this;
    var toView = e.currentTarget.dataset.optg;
    page.setData({
      toView: toView
    });
  },
  scrollTo(e) {
    let page = this,
      scrollTop = e.detail.scrollTop;

    if (
      scrollTop >= page.data.chapterBoxTop &&
      scrollTop < page.data.teacherBoxTop
    ) {
      page.setData({
        activeView: 'chapter'
      });
    } else if (scrollTop < page.data.schoolBoxTop) {
      page.setData({
        activeView: 'teacher'
      });
    } else if (scrollTop < page.data.coursesBoxTop) {
      page.setData({
        activeView: 'school'
      });
    } else {
      page.setData({
        activeView: 'courses'
      });
    }
  },
  toggleCatalog: function(e) {
    var page = this;
    var expand_status = e.currentTarget.dataset.expand;
    page.setData({
      expand: !expand_status
    });
  },
  onClose() {
    this.setData({ show: false });
  },
  onSelect(event) {
    // console.log(event.detail);
  },
  toResList: function(e) {
    var page = this;
    var id = e.currentTarget.dataset.id;
    var standard_name = e.currentTarget.dataset.standard_name;

    //  学习进度
    app.sendRequest({
      hideLoading: true,
      url: api.course.brgin_study,
      method: 'post',
      header: {
        token: wx.getStorageSync('access_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        curriculum_id: page.data.curriculum_id,
        standard_id: id
      },
      success(res) {
        if (res.status == 200) {
          page.setData({
            joined: 1,
            standard_id: id,
            standard_name: standard_name,
            text: '继续学习'
          });
          wx.navigateTo({
            url:
              '/pages/course_resource/course_resource?standard_id=' +
              id +
              '&standard_name=' +
              standard_name
          });
        } else if (res.status == 400) {
          Dialog.alert({
            message: res.msg
          }).then(() => {
            return false;
          });
        }
      }
    });
  },
  // 切换分享弹窗
  toggleShareCourse: function(e) {
    var page = this;
    page.setData({
      show: !page.data.show
    });
  },
  joinCourse: function(e) {
    var page = this;
    if (
      page.data.isIOS &&
      page.data.course_info.now_cost > 0 &&
      page.data.joined == 0
    ) {
      Dialog.alert({
        message: '因政策原因,暂不支持购买课程'
      });
      return false;
    }

    var standard_id =
      page.data.standard_id != ''
        ? page.data.standard_id
        : page.data.treeData[0].id;

    var standard_name =
      page.data.standard_id != ''
        ? page.data.standard_name
        : page.data.treeData[0].name;
    var curriculum_name = e.currentTarget.dataset.curriculum_name;
    var curriculum_id = e.currentTarget.dataset.curriculum_id;
    var params = {};
    params.curriculum_id = curriculum_id;

    if (page.data.joined == 1) {
      params.standard_id = standard_id;
    }
    app.sendRequest({
      url: app.api.course.brgin_study,
      data: params,
      method: 'POST',
      header: {
        token: wx.getStorageSync('access_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.status == 200) {
          let data = res.data;
          // 需要购买&已有订单
          if (data.status == 3 || data.status == 4) {
            if (
              // !page.data.isIOS &&
              page.data.course_info.now_cost > 0 &&
              page.data.joined == 0
            ) {
              // Dialog.alert({
              //   message: '支付功能还未上线,请先至Web端进行购买'
              // });
              wx.navigateTo({
                url:
                  '/pages/sure_buy/sure_buy?curriculum_id=' +
                  page.data.curriculum_id +
                  '&status=' +
                  data.status
              });
            }
          } else if (data.status == 1) {
            page.setData({
              joined: 1,
              standard_id: standard_id,
              standard_name: standard_name,
              text: '继续学习'
            });
            wx.navigateTo({
              url:
                '/pages/course_resource/course_resource?standard_id=' +
                standard_id +
                '&standard_name=' +
                standard_name
            });
          }
        } else if (res.status == 400) {
          Dialog.alert({
            message: res.msg
          }).then(() => {
            return false;
          });
        }
      }
    });
  },
  findMore: function(e) {
    wx.navigateTo({
      url: '/pages/course_filter/course_filter'
    });
  },

  toTeacherDetail: function(e) {
    var teacher_id = e.currentTarget.dataset.id;
    var teacher_title = e.currentTarget.dataset.title;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url:
        '../teacher_detail/teacher_detail?teacher_id=' +
        teacher_id +
        '&teacher_title=' +
        teacher_title +
        '&name=' +
        name
    });
  },

  toCourse: function(e) {
    var cid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/course_detail/course_detail?curriculum_id=' + cid
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var page = this;
    if (page.data.show) {
      page.setData({
        show: false
      });
    }

    let complete_standard = wx.getStorageSync('current_complete_standard'),
      treeData = page.data.treeData;
    if (complete_standard != undefined) {
      treeData.map((t_item_1, index_1) => {
        if (t_item_1.id == complete_standard) {
          t_item_1.if_start = 1;
          return false;
        }
        if (t_item_1.child.length > 0) {
          t_item_1.child.map((t_item_2, index_2) => {
            if (t_item_2.id == complete_standard) {
              t_item_2.if_start = 1;
              return false;
            }
          });
        }
      });
      page.setData({
        treeData: treeData
      });
    }

    wx.getSystemInfo({
      success: function(res) {
        let scrollViewHeight = page.data.isIPX
          ? res.windowHeight - 1
          : res.windowHeight - 31;
        page.setData({
          scrollViewHeight: scrollViewHeight
        });
      }
    });

    page.updateStudyPro();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    if (this._observer) this._observer.disconnect();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
